package batch;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import threshold.MaxNDCRThresholdFinder;
import threshold.ThresholdFactory;
import dao.FileIO;
import dao.OutputFile;

public class BatchBalancer {

	public void proceed(String[] args) {
		
		String fileListFile = args[0];
		String thresholdType = args[1];
		List<String> remain = new ArrayList<String>(args.length - 2);
		for(int i = 2; i < args.length; i++) {
			remain.add(args[i]);
		}
		
		List<String> lines = FileIO.readFile(fileListFile);
		Iterator<String> itr = lines.iterator();
		itr.next();
		double threshold = getThreshold(itr.next().split(" ")[1], thresholdType, remain);
		
		while(itr.hasNext()) {
			String [] tokens = itr.next().split(" ");
			String probFile = tokens[1];
			String resultFile = tokens[2];
			proceedOneFile(probFile, resultFile, threshold);
		}
	}
	
	protected double getThreshold(String filename, String thtype, List<String> args){
		
		MaxNDCRThresholdFinder finder = ThresholdFactory.getFinder(thtype);
		finder.initialize(args);
		
		List<String> lines = FileIO.readFile(filename);
		List<Integer> labelList = new ArrayList<Integer>(lines.size() - 1);
		List<Double> probList = new ArrayList<Double>(lines.size() - 1);
		Iterator<String> itr = lines.iterator();
		itr.next();
		
		while(itr.hasNext()) {
			String line = itr.next();
			int label = line.charAt(0) - '0';
			double prob = Double.parseDouble(line.substring(2, line.length() - 2));
			labelList.add(label);
			probList.add(prob);
		}
		
		double thresh = finder.find(labelList, probList);
		
		return thresh;
	}
	
	protected void proceedOneFile(String probFile, String resultFile, double threshold) {
		List<String> lines = FileIO.readFile(probFile);
		Iterator<String> itr = lines.iterator();
		itr.next();
		
		List<Double> logProbList = new ArrayList<Double>(lines.size() - 1);
		List<Integer> labelList = new ArrayList<Integer>(lines.size() - 1);
		while(itr.hasNext()) {
			String line = itr.next();
			double prob = Double.parseDouble(line.substring(2, line.length() - 2));
			int label = prob >= threshold ? 1 : 0;
			logProbList.add(prob);
			labelList.add(label);
		}
		
		OutputFile fout = new OutputFile();
		fout.open(resultFile);
		
		fout.write("label 1 0\n");
		
		Iterator<Integer> lItr = labelList.iterator();
		Iterator<Double> pItr = logProbList.iterator();
		while(lItr.hasNext()){
			int label = lItr.next();
			double prob = pItr.next();
			fout.write(label + " " + prob + " 0\n");
		}
		
		fout.close();
	}
	
	public static void main(String[] args) {
		BatchBalancer m = new BatchBalancer();
		m.proceed(args);
	}
}
